(function(){
	/**
	 * 微场景 
	 * @author rubekid
	 */

	/**
	 * 浏览器样式前缀
	 */
	var prefix = (function () {
	  var styles = window.getComputedStyle(document.documentElement, ''),
		pre = (Array.prototype.slice
		  .call(styles)
		  .join('')
		  .match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])
		)[1],
		dom = ('WebKit|Moz|MS|O').match(new RegExp('(' + pre + ')', 'i'))[1];
	  return {
		dom: dom,
		lowercase: pre,
		css: '-' + pre + '-',
		js: pre[0].toUpperCase() + pre.substr(1)
	  };
	})();
	
	var translateCss = function(css){
		var style = {};
		for(var i in css){
			style[i.replace('{prefix}', prefix.css)]  =  typeof css[i] == "number" ? (css[i]+"") : css[i].replace('{prefix}', prefix.css);
			//style[i.replace('{prefix}', '')]  = typeof css[i] == "number" ? (css[i]+"") : css[i].replace('{prefix}', '');
		}
		return style;
	};
	
	/**
	 * 浏览器辅助函数
	 */
	var BrowserHelper = (function(){
		var ua = navigator.userAgent.toLowerCase();
		var check = function(r){
			return r.test(ua);
		};
		browser = {};
		browser.isUcbrowser = check(/ucbrowser/);
		browser.isIphone = check(/iphone/);
	    browser.isIpad	= check(/ipad/);
	    browser.isIOS = browser.isIpad || browser.isIphone;
	    browser.isIOSUC = browser.isIOS && browser.isUcbrowser;
		return browser;
	})();
	
	/**
	 *  requestAnimationFrame
	 *  cancelAnimationFrame
	 */
	(function() {
	    var lastTime = 0;
	    var vendors = ['webkit', 'moz', 'ms', 'o'];
	    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
	        window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
	        window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] ||    // Webkit中此取消方法的名字变了
	                                      window[vendors[x] + 'CancelRequestAnimationFrame'];
	    }
	
	    if (!window.requestAnimationFrame) {
	        window.requestAnimationFrame = function(callback, element) {
	            var currTime = new Date().getTime();
	            var timeToCall = Math.max(0, 16.7 - (currTime - lastTime));
	            var id = window.setTimeout(function() {
	                callback(currTime + timeToCall);
	            }, timeToCall);
	            lastTime = currTime + timeToCall;
	            return id;
	        };
	    }
	    if (!window.cancelAnimationFrame) {
	        window.cancelAnimationFrame = function(id) {
	            clearTimeout(id);
	        };
	    }
	}());
	
	var touchStart = ('ontouchstart' in window) ? "touchstart" :"click";
	
	function log(message){
		document.title = message;
	}
	
	var SceneConfig = window.SceneConfig ||{};
	window.SceneConfig = SceneConfig;
	
	/**
	 * 类的继承
	 * @param subClass
	 * @param superClass
	 * @param properties
	 */
	function inherits(subClass, superClass, properties){	
		properties = properties ||{};
	    var F = function(){};
	    F.prototype = superClass.prototype;
	    //创建拷贝,不影响父类
		var nF=new F();
		//扩展子类方法		
		for(var key in properties){
			nF[key] = properties[key];
		}
		subClass.prototype=nF;
	    subClass.prototype.constructor = subClass;
	    subClass.superclass = superClass.prototype; //加了个属性指向父类本身以便调用父类函数
	    if(superClass.prototype.constructor == Object.prototype.constructor){
	        superClass.prototype.constructor = superClass;
	    }
	}
	
	/**
	 * 点 
	 */
	function Point(options){
		this.init(options);
	}
	
	Point.prototype = {
		init:function(options){
			this.initCanvas(options);
		},
		initCanvas:function(options){
			var canvas = document.createElement("canvas");
			var radius = options.radius;
			canvas.width = radius * 2;
			canvas.height = canvas.width;
			var context = canvas.getContext("2d");
			
			context.fillStyle = "rgba(255, 255, 255, 1)";
			context.beginPath();
			context.arc(radius, radius, radius / 2 , 0, 2 * Math.PI);
			context.fill();
			
			context.strokeStyle= "rgba(255, 255, 255, 0.40)";
			context.beginPath();
			context.arc(radius, radius, radius * 3 / 4 , 0, 2 * Math.PI);
			context.lineWidth = 3;
			context.stroke();
			this.canvas = canvas;
		},
		getElement:function(){
			return this.canvas;
		}
	}
	
	/**
	 * 刮刮卡 
	 */
	function Scratch(options){
		this.init(options);	
	}
	
	Scratch.prototype = {
		init:function(options){
			this.type = options.type || Scratch.TYPE_ERASE; // 0:擦除效果 1:点击效果
			this.threshold = options.threshold || 0;//触发完成临界覆盖率
			this.ratio = options.ratio||10;//分解比例
			this.initCanvas(options);
			this.onClearAll = options.onClearAll || function(){};
		},
		initCanvas:function(options){
			var wrapper = options.wrapper;
			var coverImage = options.coverImage;
			var width = options.width;
			var height = options.height;
			var canvas = document.createElement("canvas");
			canvas.className = "listener_resize";
			wrapper.appendChild(canvas);
			canvas.width = width;
			canvas.height = height;
			canvas.style.position = "relative";
			canvas.style.zIndex = 2;
			var context = canvas.getContext("2d");
			var image = new Image();
			var _this = this;
			this.canvas = canvas;
			image.onload = function(){
				context.drawImage(image, 0, 0, width, height);
				var copyCanvas = document.createElement("canvas");
				copyCanvas.width = width;
				copyCanvas.height = height;
				var copyContext = copyCanvas.getContext('2d');
				copyContext.drawImage(image, 0, 0, width, height);
				_this.copyCanvas = copyCanvas;
				if(_this.type == Scratch.TYPE_EXPLODE){
					_this.initTiles();
					_this.initPoints(wrapper, width , height, options.pointSize||3);
				}
				else if(_this.type == Scratch.TYPE_STAMP){
					_this.initStamps();
					_this.initPoints(wrapper, width , height, options.pointSize||3);
				}
				_this.bindEvent();
			};
			image.src = coverImage;
			
			
		},
		initPoints:function(wrapper, width, height, size){
			this.points = [];
			var deg = 2* Math.PI / size;
			for(var  i = 0; i < size; i ++){
				var random = Math.random() * deg * 150 / 2;
				var x = Math.sin( random) * Math.random() * 50 ;
				var y = Math.cos( random) * Math.random() * 50;  
				var point = new Point({
					radius:22
				});
				var canvas = point.getElement();
				var div = document.createElement("div");
				div.style.position = "absolute";
				div.style.zIndex = "2";
				div.appendChild(canvas);
				wrapper.appendChild(div);
				canvas.style.position = "relative";
				canvas.style.left= x + "px";
				canvas.style.top = y + "px";
				canvas.className = "fade filter_touch";
				this.points.push(point);
				if(i%3==0){
					div.style.left = "20%";
					div.style.top = "20%";
				}
				else if(i%3==1){
					div.style.right = "20%";
					div.style.top = "20%";
				}
				else if(i%3==2){
					div.style.left = "50%";
					div.style.bottom = "20%";
				}
				
			}
		},
		initTiles:function(){
			var ratio = this.ratio;
			var width = this.canvas.width;
			var height = this.canvas.height;
			this.tileWidth = width / ratio;
			this.tileHeight = height/ratio;
			this.tileCenterWidth = this.tileWidth / 2;
			this.tileCenterHeight = this.tileHeight /2;
			this.tiles = [];
			var x = 0;
			var y = 0;
			while(x < width){
				var y = 0;
				while(y < height){
					var tile = {
						x:x,
						y:y,
						currentX : x + this.tileCenterWidth,
						currentY : y + this.tileCenterHeight,
						rotation : 0,
						force:0
					}
					this.tiles.push(tile);
					y +=this.tileHeight;
				}
				x += this.tileWidth;
			}
			this.copyCanvas.width = width;
			this.copyCanvas.height = height;
			var context = this.copyCanvas.getContext('2d');
			context.drawImage(this.canvas, 0, 0, width, height);
		},
		initStamps:function(){
			this.stamps = [];
			var slices = SceneConfig.stampSlices;
			var _this = this;
			var image = new Image();
			image.onload = function(){
				for(var i=0; i< slices.length; i++){
					var slice = slices[i];
					var canvas = document.createElement("canvas");
					canvas.width = slice.w;
					canvas.height = slice.h;
					var ctx = canvas.getContext("2d");
					ctx.drawImage(this , slice.x, slice.y, slice.w, slice.h, 0, 0, slice.w, slice.h);
					_this.stamps.push(canvas);
				}
			};
			image.src = SceneConfig.stampImage;
		},
		resize:function(){
			if(!this.isClear){
				var context = this.canvas.getContext('2d');
				var width = window.innerWidth || this.canvas.width;
				var height = window.innerHeight || this.canvas.height;
				this.canvas.width = width;
				this.canvas.height = height;
				context.drawImage(this.copyCanvas, 0, 0, width, height);
				if(this.type == Scratch.TYPE_EXPLODE){
					this.initTiles();
				}
			}
		},
		bindEvent:function(){
			var _this = this;
			var canvas = this.canvas;
			if(this.type == Scratch.TYPE_EXPLODE){
				var size = this.points.length;
				var downCount = size;
				this.interval = null;
				var clickEvent = function(event){
					event.preventDefault();
					if(!_this.interval){
						_this.interval = setInterval(function(){
							_this.explodeProcess();
						}, 30);
					}
					var pageX = event.pageX || event.clientX;
					var pageY = event.pageY || event.clientY;
					if(event.type == "touchstart"){
						pageX = event.touches[0].pageX;
						pageY = event.touches[0].pageY;
					}
					var x = pageX - canvas.offsetLeft;
					var y = pageY - canvas.offsetTop;
					this.parentNode.removeChild(this);
					_this.explode(x, y);
					downCount --;
					if(downCount == 0){
						setTimeout(function(){
							_this.clear();
							_this.onClearAll();
							if(_this.interval){
								clearInterval(_this.interval);
							}
						},800);
					}
				};
				for(var i=0; i< size; i++){
					var point = this.points[i];
					point.getElement().addEventListener(touchStart, clickEvent, false);
				}
			}
			else if(this.type == Scratch.TYPE_STAMP){
				var size = this.points.length;
				var downCount = size;
				var clickEvent = function(event){
					event.preventDefault();
					var pageX = event.pageX || event.clientX;
					var pageY = event.pageY || event.clientY;
					
					if(event.type == "touchstart"){
						pageX = event.touches[0].pageX;
						pageY = event.touches[0].pageY;
					}
					var x = pageX - canvas.offsetLeft;
					var y = pageY - canvas.offsetTop;
					this.parentNode.removeChild(this);
					var r = Math.random() * 100 + 150;
					_this.stampErase(x, y, r);
					downCount --;
					if(downCount == 0){
						var time = 0;
						var width = _this.canvas.width;
						var height = _this.canvas.height;
						var _interval = setInterval(function(){
							var r = Math.random() * 100 + 150;
							var x = Math.random() * width;
							var y = Math.random() * height;
							_this.stampErase(x, y, r);
							time+=30;
							if(time > 800){
								clearInterval(_interval);
								_this.clear();
								_this.onClearAll();
							}
						},30);
					}
				};
				for(var i=0; i< size; i++){
					var point = this.points[i];
					point.getElement().addEventListener(touchStart, clickEvent, false);
				}
			}
			else{
				new TouchesManager({
					element:canvas,
					onTouchMove:function(startTouches, currentTouches){
						if(currentTouches.length > 0){
							var pageX = currentTouches[0].pageX;
							var pageY = currentTouches[0].pageY;
							var x = pageX - canvas.offsetLeft;
							var y = pageY - canvas.offsetTop;
							var r = 25;
							_this.erase(x, y, r);
						}
					},
					onTouchEnd:function(startTouches, currentTouches){
						_this.checkErase();
					}
				});
			}
			
			var _this = this;
		
			$(window).bind("resize", function(){
				_this.resize();
			});

		},
		erase:function(x, y, r){
			var canvas = this.canvas;
			var context = canvas.getContext('2d');
			context.globalCompositeOperation = 'destination-out';
			context.beginPath()
			context.arc(x, y, r, 0, Math.PI * 2);
			context.closePath();
			context.fill();
		},
		stampErase:function(x, y, r){
			var canvas = this.canvas;
			var context = canvas.getContext('2d');
			var index = Math.floor(this.stamps.length * Math.random());
			var stamp = this.stamps[index];
			var width = stamp.width;
			var height = stamp.height;
			var ratio = (r/width) > (r/height) ? (r/width) : (r/height);
			width = width * ratio;
			height = height * ratio;
			x -= width /2;
			y -= height /2;
			context.globalCompositeOperation = 'destination-out';
			context.beginPath();
			context.drawImage(stamp,0, 0, stamp.width, stamp.height, x, y, width, height);
			context.closePath();
			context.fill();
		},
		checkErase:function(){
			var canvas = this.canvas;
			var context = canvas.getContext('2d');
			var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
			var rate = this.getCoverRate(imageData);
			if(rate <= this.threshold){
				this.clear();
				this.onClearAll();
			}
		},
		explode:function(x, y){
			var tiles = this.tiles;
			var _this = this;
			for(var i=0; i<tiles.length; i++){
				var tile = tiles[i];
				var xdiff = tile.x-x;
				var ydiff = tile.y-y;
				var dist = Math.sqrt(xdiff*xdiff + ydiff*ydiff);
				var randRange = 220+(Math.random()*30);
				var range = randRange-dist;
				var force = 3*(range/randRange);
				if(force > tile.force){
					tile.force = force;
					var radians = Math.atan2(ydiff, xdiff);
					tile.moveX = Math.cos(radians);
					tile.moveY = Math.sin(radians);
					tile.moveRotation = 0.5-Math.random();
				}
			}
		},
		explodeProcess:function(){
			var tiles = this.tiles;
			var canvas = this.canvas;
			var context = canvas.getContext('2d');
			context.clearRect(0, 0, canvas.width, canvas.height);
			for(var i=0; i<tiles.length; i++){
				var tile = tiles[i];
				if(tile.force > 0.0001){
					tile.moveX *= tile.force;
					tile.moveY *= tile.force;
					tile.moveRotation *= tile.force;
					tile.currentX += tile.moveX;
					tile.currentY += tile.moveY;
					tile.rotation += tile.moveRotation;
					tile.rotation %= 360;
					tile.force *= 0.9;
					if(tile.currentX <= 0 || tile.currentX >= canvas.width){
						tile.moveX *= -1;
					}
					if(tile.currentY <= 0 || tile.currentY >= canvas.height){
						tile.moveY *= -1;
					}
					isEnd = false;
				}
				context.save();
				context.translate(tile.currentX, tile.currentY);
				context.rotate(tile.rotation* Math.PI / 180);
				context.drawImage(this.copyCanvas, tile.x, tile.y, this.tileWidth, this.tileHeight, - this.tileCenterWidth, - this.tileCenterHeight, this.tileWidth, this.tileHeight);
				
				context.restore();
			}
		},
		clear:function(){
			this.isClear = true;
			var context = this.canvas.getContext("2d");
			context.clearRect(0, 0, this.canvas.width, this.canvas.height);
			this.canvas.parentNode.removeChild(this.canvas);
		},
		getCoverRate:function(pixels){
			var d = pixels.data;
			var count = 0;
		    for (var i = 0; i < d.length; i += 4) {
		    	if(d[i] == 0 && d[i + 1] == 0 && d[i + 2] ==0){
		    		count ++ ;
		    	}
		    }
		    return  1 - count / (d.length /4);
		}
	};
	
	Scratch.TYPE_ERASE = 0;
	Scratch.TYPE_STAMP = 1;
	Scratch.TYPE_EXPLODE = 2;
	
	
	
	/**
	 * 页面工厂 
	 */
	var PageFactory = {
		/**
		 * 页面类型 -图文（普通类型） 
		 */
		TYPE_NORMAL : 0,
		
		/**
		 * 页面类型 - 视频 
		 */
		TYPE_VIDEO : 1,
		
		/**
		 * 页面类型 - 动画 
		 */
		TYPE_ANIMATION : 2,
		creator:function(options){
			var type = options.type|| 0; //0:图文页面,1:视频页面，2：动画页面
			if(type == this.TYPE_VIDEO){
				return new VideoPage(options);
			}
			else if(type == this.TYPE_ANIMATION){
				return new AnimationPage(options);
			}
			else {
				return new NormalPage(options);
			}
		}
	};
	
	
	
	/**
	 * 页面 
	 */
	function Page(options){
		this.init(options);
	}
	
	Page.prototype = {
		init:function(options){
			this._srcList = this.getImages(options);
			this.element = $('<section class="main_page"></section>');
			this.container = $('<div class="scene_bg"></div>');
			this.element.append(this.container);
			this.container.css({
				"background-image":"url('"+options.bgImage+"')",
				"background-color":"#FFFFFF"
			});
			this.scene = options.scene;
			this.lockState = false;
			this.initData(options);
			if(options.showArrow){
				this.createArrow(options);
			}
			
			this.initHtml(options);
		},
		initData:function(options){
			throw new Error("Must implement the inherited abstract method initData()");
		},
		initHtml:function(options){
			throw new Error("Must implement the inherited abstract method initHtml()");
		},
		getImages:function(options){ //获取所有的图片
			throw new Error("Must implement the inherited abstract method getImages()");
		},
		createArrow:function(options){
			var arrow = $('<div class="scene_arrow"></div>');
			arrow.addClass(options.arrowClassName);
			this.append(arrow);
			if(!BrowserHelper.isIOSUC){
				arrow.css({
					"position":"fixed"
				});
			}
		},
		/**
		 * append后执行  兼容有些需要实时高度和宽度 
		 */
		afterAppend:function(){},
		onShow:function(){},//显示时触发
		onHide:function(){},//隐藏时触发
		getElement:function(){
			return this.element;
		},
		find:function(selector){
			return $(selector, this.container);
		},
		getSrcList:function(){
			return this._srcList;
		},
		outerWidth:function(){
			return this.container.width();
		},
		outerHeight:function(){
			return this.container.height();
		},
		lock:function(){
			this.lockState = true;
		},
		unlock:function(){
			this.lockState = false;
		},
		isLocked:function(){
			return this.lockState;
		},
		append:function(element){
			this.container.append(element);
		},
		addClass:function(className){
			this.element.addClass(className);	
		},
		removeClass:function(className){
			this.element.removeClass(className);
		},
		addContainerClass:function(className){
			this.container.addClass(className);	
		},
		removeContainerClass:function(className){
			this.container.removeClass(className);
		},
		removeSiblingsClass:function(className){
			this.element.siblings().removeClass(className);
		},
		replaceSiblingsClass:function(className, newClassName){
			this.element.siblings("."+className).removeClass(className).addClass(newClassName);
		},
		css:function(css){
			this.element.css(translateCss(css));
		},
		setContainerStyle:function(css){
			this.container.css(translateCss(css));
		},
		show:function(){
			this.element.show();
		},
		hide:function(){
			this.element.hide();
		}
	};
	
	Page.extends = function(properties){
		var subClass = function(options){
			this.init(options);
		};
		inherits(subClass, Page, properties);
		return subClass;
	};

	
	/**
	 * 普通页面 
	 */
	var NormalPage = Page.extends({
		getImages:function(options){
			var images = [];
			if(options.bgImage){
				images.push(options.bgImage);
			}
			if(options.useCover){
				options.coverImage = options.coverImage || SceneConfig.defaultCoverImage;
				images.push(options.coverImage);
				if(options.coverType == Scratch.TYPE_STAMP){
					images.push(SceneConfig.stampImage);
				}
			}
			return images;
		},
		initData:function(options){
			this.tipText = options.tipText;
			this.type = options.type;
			this.buttonList = options.buttionList;
			if(options.useCover){
				this.coverType  = options.coverType;
				this.coverImage = options.coverImage;
				this.threshold = options.threshold;
			}
		},
		initHtml:function(options){
			this.buttonContainer = $('<div class="button_container"></div>');
			if(options.useButton){
				var rowType = options.buttonType ? 2 : 1;
				var row = $('<div class="button_row"></div>');
				for(var i=0; i< options.buttons.length ; i++){
					var button = options.buttons[i];
					if(i % rowType == 0){
						row = $('<div class="button_row"></div>');
						this.buttonContainer.append(row);
					}
					
					if(button.type == 1){
						row.append('<a href="'+button.href+'" class="scene_button scene_button_'+(button.style + 1)+'">'+button.text+'</a>');
					}
					else{
						row.append('<a href="'+button.href+'" class="scene_button scene_image_button" style="background-image:url(\''+button.bgImage+'\')">&nbsp;</a>');
					}
					
				}
				this.append(this.buttonContainer);
				this.buttonPosition = options.buttonPosition;
			}
			
		},
		afterAppend:function(){
			if( this.coverImage){
				this.createCover();
			}
			if(this.buttonContainer){
				var width = this.buttonContainer.width();
				var css = {
					left:"50%",
					marginLeft : -width/2+"px"
				};
				if(this.buttonPosition == 1){
					var height = this.buttonContainer.height();
					css.top = "50%";
					css.marginTop = -height/2+"px";
				}
				else if(this.buttonPosition == 2){
					css.top = "10%";
				}
				else{
					css.bottom = "10%";
				}
				this.buttonContainer.css(css);
			}
		},
		createCover:function(){
			this.lock();
			var _this = this;
			var tip = $('<div></div>');
			tip.text(this.tipText);
			tip.addClass("cover_tip");
			this.container.append(tip);
			new Scratch({
				type:this.coverType,
				threshold:0.9,
				wrapper:this.container.get(0),
				width:this.outerWidth(),
				height:this.outerHeight(),
				coverImage:this.coverImage,
				onClearAll:function(){
					tip.remove();
					setTimeout(function(){
						_this.unlock();
						_this.onShow();
					},1000);
					
				}
			});
			
		}
		
	});
	
	/**
	 * 视频页面 
	 */
	var VideoPage = Page.extends({
		getImages:function(options){
			var images = [];
			if(options.bgImage){
				images.push(options.bgImage);
			}
			if(options.cover){
				images.push(options.cover);
			}
			return images;
		},
		initData:function(options){
			this.title = options.title;
			this.cover = options.cover;
			this.description = options.description;
			this.url = options.url;
		},
		initHtml:function(options){
			var video = options.video;
			var html = '<div class="scene_video"><a href="javascript:;"><i class="video_btn"></i></a><img src="'+this.cover+'"/></div>'
							+'<div class="scene_video_txt">'
							  +'<h2>'+this.title+'</h2>'
							  + this.description
						+'</div>';
			this.videoDialog = $('<div class="video_dialog">'
									+'<iframe width="100%" frameborder="0" allowfullscreen="true" security="restricted" sandbox="" src="'+this.url+'" style="position: absolute;min-height: 45%; max-height: 100%; top: 20%;"></iframe>'
									+'<a class="btn_close_dialog" href="javascript:;"></a>'
								+'</div>');
						
			this.append(html);
			var _this = this;
			this.find(".video_btn").bind(touchStart, function(){
				_this.lock();
				_this.append(_this.videoDialog);
				_this.scene.onDialogShow();
				
			});		
			this.videoDialog.find(".btn_close_dialog").bind(touchStart, function(){
				_this.unlock();
				_this.videoDialog.detach();
				_this.scene.onDialogHide();
			});
		}
		
	});
	
	var AnimationClasses = {
		1:"fadeIn",
		2:"fadeInRight",
		3:"wobble",
		4:"rubberBand",
		5:"rotateIn",
		6:"flip",
		7:"swing",
		8:"bounceInRight",
		9:"bounceIn",
		10:"zoomIn",
		11:"fadeOut",
		12:"flipOut"
	};
	
	/**
	 * 视频页面 
	 */
	var AnimationPage = Page.extends({
		getImages:function(options){
			var images = [];
			if(options.bgImage){
				images.push(options.bgImage);
			}
			if(options.elements){
				for(var i=0; i< options.elements.length; i++){
					var element = options.elements[i];
					if(element.type==0){
						images.push(element.image);
					}
				}
			}
			return images;
		},
		initData:function(options){
			this.tipText = options.tipText;
			this.type = options.type;
			this.animations = [];
		},
		initHtml:function(options){
			
			var elements = options.elements;
			if(elements){
				for(var i = 0; i< elements.length; i++){
					var element = elements[i];
					var node = $('<a href="'+element.href+'" class="animate_item"></a>');
					if(element.type == 1){
						node.html('<pre>' +element.text+'</pre>');	
					}
					else{
						node.html('<img src="'+element.image+'" width="120" />');
					}
					var wrapper = $('<div></div>');
					wrapper.append(node);
					this.append(wrapper);
					var left = 0, top=0, wrapperCss={}, isCenter=false;
					//position 0:居中       1：左上      2右上        3左下        4 右下
					
					if(element.position == 1){
						wrapperCss = {
							left : "10%",
							top : "10%"
						};
					}
					else if(element.position == 2){
						wrapperCss = {
							right : "10%",
							top : "10%"
						};
						
					}
					else if(element.position == 3){
						wrapperCss = {
							left : "10%",
							bottom : "10%"
						};
						
					}
					else if(element.position == 4){
						wrapperCss = {
							right : "10%",
							bottom : "10%"
						};
						
					}
					else {
						wrapperCss = {
							top : "50%",
							left : "50%"
						};
						isCenter = true;
					}
					wrapper.css(wrapperCss);
					node.css({
							left:element.left,
							top:element.top
					});
					wrapper.addClass("element_wrapper");
					node.addClass("page_element");
					wrapper.hide();
					var timeout = 0;
					var count = element.count || 1;
					var duration = element.duration || 2;
					var delay = element.delay || 0;
					if(count > 0){
						timeout = delay + count * duration;
					}
					var animationStyle = {
						"{prefix}animation-duration" : duration +"s", 
						"{prefix}animation-delay" : delay +"s",
						"{prefix}animation-iteration-count":count
					};
					this.animations.push({
						target:wrapper,
						element:node,
						className:AnimationClasses[element.style]||"",
						style:translateCss(animationStyle),
						isCenter:isCenter,
						timeout:timeout * 1000
					});
				}
			}
		},
		onShow:function(){
			for(var i=0; i<this.animations.length; i++){
				var animation = this.animations[i];
				var target = animation.target;
				var element = animation.element
				target.show();
				if(animation.className){
					element.addClass(animation.className);
				}
				if(!animation.hasInit){
					element.css(animation.style);
					if(animation.isCenter){
						content = animation.content;
						width = element.width();
						height = element.height();
						target.css({
							marginTop: -height / 2 + "px",
							marginLeft: -width / 2 + "px"
						});
					}
					animation.hasInit= true;
				}
				
				if(animation.timeout && animation.className){
					(function(a){
						setTimeout(function(){
							a.element.removeClass(a.className);
						}, a.timeout);
					})(animation);
					
				}
			}
		},
		clearAnimation:function(){
			for(var i=0; i<this.animations.length; i++){
				var animation = this.animations[i];
				animation.target.hide();
				if(animation.className){
					animation.element.removeClass(animation.className);
				}
			}
		},
		onHide:function(){
			this.clearAnimation();
		}
	});
	
	
	/***********************************************/
	
	
	
	/**
	 * 微场景管理器 
	 */
	function SceneManager(options){
		this.init(options);
	}
	
	SceneManager.prototype = {
		init:function(options){
			var sceneType = options.sceneType; //# 场景效果：0、上下滑动，1、左右滑动，2、上下展开，3、左右展开
			
			if(sceneType === 0){
				options.style = SceneBase.STYLE_COVER;
				options.type = SceneBase.TYPE_UP;
			}
			else if(sceneType == 1){
				options.style = SceneBase.STYLE_COVER;
				options.type = SceneBase.TYPE_LEFT;
			}
			else if(sceneType == 2){
				options.style = SceneBase.STYLE_UNFOLD;
				options.type = SceneBase.TYPE_UP;
			}
			else if(sceneType == 3){
				options.style = SceneBase.STYLE_UNFOLD;
				options.type = SceneBase.TYPE_LEFT;
			}
			else if(sceneType == 4){
				options.style = SceneBase.STYLE_3D_OUT;
				options.type = SceneBase.TYPE_UP;
			}
			
			var style = options.style || SceneBase.TYPE_TRANSLATE; //0:普通切换,1:覆盖切换,2:缩放切换 ,3:3D切换
			if(style == SceneBase.STYLE_COVER){
				this.scene = new CoverScene(options);
			}
			else if(style == SceneBase.STYLE_SCALE){
				this.scene = new ScaleScene(options);
			}
			else if(style == SceneBase.STYLE_UNFOLD){
				this.scene = new UnfoldScene(options);
			}
			else if(style == SceneBase.STYLE_3D_IN){
				this.scene = new Scene3DIn(options);
			}
			else if(style == SceneBase.STYLE_3D_OUT){
				this.scene = new Scene3DOut(options);
			}
			else{
				this.scene = new TranslateScene(options);
			}
		}
		
		
	};
	
	/**
	 * 微场景基类 
	 */
	function SceneBase(options){
		this.init(options);	
	}
	
	SceneBase.prototype = {
		init:function(options){
			options = options ||{};
			this.container = options.container;
			this.pages = [];
			this.readyCount = 0;
			this.pageCount = 0;
			this.threshold = options.threshold||0.5;//速度阀值
			this.type = options.type || 0; //0:向上，1：向下，2:向左，3：向右
			this.initType();
			this.bgMusic = options.useBackmusic ? options.backmusicUrl : null;
			this.initHtml(options.pages);
		},
		initType:function(){
			this.xType = 0; //横轴方向类型
			this.dType = 1; //方向类型 1:正方向 -1 负方向
			if(this.type == 2 || this.type == 3){
				this.xType = 1;
			}
			
			if(this.type == 1 || this.type == 3){
				this.dType = -1;
			}
		},
		initHtml:function(pages){
			this.initLoading();
			this.createAudio();
			if(pages){
				this.pageCount = pages.length;
				var arrowClassName = "scene_arrow_t";
				if(this.type == 1){
					arrowClassName  = "scene_arrow_b";
				}
				else if(this.type == 2){
					arrowClassName  = "scene_arrow_l";
				}
				else if(this.type == 3){
					arrowClassName  = "scene_arrow_r";
				}
				
				var _this = this;
				var images = [];
				for(var i =0; i< pages.length; i++){
					var data = pages[i];
					$.extend(data, {
						arrowClassName:arrowClassName,
						scene:_this,
						showArrow:this.pageCount > 1
					});
					var page = PageFactory.creator(data);
					this.container.append(page.getElement());
					this.pages.push(page);
					page.afterAppend();
					page.hide();
					images = images.concat(page.getSrcList());
				}
				if(this.pages.length > 0){
					this.setCurrentPage(this.pages[0]);
					this.activePage = this.currentPage;
				}
				
				
				this.imageSize = images.length;

				if(this.imageSize == 0){
					this.ready();
				}
				else{

					var _this = this;
					var loaded = function(){
						_this.ready();
					};
					this.progress();
					for(var i=0; i<this.imageSize; i++){
						var image = new Image();
						image.onload = loaded;
						image.onerror = loaded;
						image.src = images[i];
					}
					
				}
				
			}
		},
		initLoading:function(){
			this.loadPage = this.find('.loading_page');
			this.loadPercentTarget = this.find(".j_percent");
			this.loading = true;
			this.loaded = 0;
		},
		createAudio:function(){
			if(this.bgMusic){
				this.playMusicBtn = $('<a href="javascript:;" id="btn_play_music" class="scene_music"></a>');
				this.container.after(this.playMusicBtn);
				this.audio = new Audio(this.bgMusic);
				this.audio.loop = true;
				this.audio.load();
			}
		},
		onDialogHide:function(){
			if(this.playMusicBtn){
				this.playMusicBtn.show();
				if(this.resumeMusic){
					this.audio.play();
				}
			}
		},
		onDialogShow:function(){
			if(this.playMusicBtn){
				if(!this.audio.paused){
					this.audio.pause();
					this.resumeMusic = true;
				}
				else{
					this.resumeMusic = false;
				}
				this.playMusicBtn.hide();
			}
		},
		removeLoading:function(){
			this.loading = false;
			this.loadPage.find(".loading").hide();
			this.loadPage.find(".half_part").addClass("open");
			var _this = this;
			setTimeout(function(){
				_this.loadPage.remove();
			},1000);
			
		},
		initCoords:function(x, y){
			var data = {};
			if(this.xType == 0){
				y = y || 0;
				data = {
					name:"Y",
					other:"X",
					value: y,
					max:this.container.height()
				};
			}
			else{
				x = x || 0;
				data = {
					name:"X",
					other:"Y",
					value: x,
					max:this.container.width()
				};
			}
			return data;
		},
		ready:function(){
			this.readyCount ++;
			if(this.readyCount == this.imageSize){
				if(this.lHander){
					clearInterval(this.lHander);
				}
				this.loadPercentTarget.text(100);
				this.onReady();	
			}
			else{
				this.progress(this.readyCount);
			}
		},
		onReady:function(){
			this.removeLoading();
			this.bindEvent();
		},
		progress:function(value){
			value = value || 0;
			this.loaded = this.expectLoaded || 0;
			this.expectLoaded = Math.ceil((value +1 ) / this.imageSize * 10000 ) /100;
			if(this.expectLoaded > 100){
				this.expectLoaded = 100;
			}
			if(this.lHander){
				clearInterval(this.lHander);
			}
			var _this = this;
			this.lHander = setInterval(function(){
				_this.loaded ++;
				if(_this.loaded < _this.expectLoaded){
					_this.loadPercentTarget.text(_this.loaded);
				}
				else{
					clearInterval(_this.lHander);
				}
			}, 30);
		},
		bindEvent:function(){
			var _this = this;
			
			document.addEventListener("scroll.elasticity", function(e) {
				e.preventDefault();
			}, false);
			document.addEventListener("touchmove.elasticity", function(e) {
				e.preventDefault();
			}, false);
			document.body.onselectstart=function(){return false;};
			this.find("img").bind("touchmove,mousemove", function(e){
				e.preventDefault();
			});
			if(this.pages.length > 1){
				var touchesManager = new TouchesManager({
					element:this.container.get(0),
					filter:function(e){
						if(e.target.tagName.toLowerCase() == "a" || $(e.target).closest("a").length > 0){
							return true;
						}
						else if($(e.target).hasClass("filter_touch")){
							return true;
						}
						return false;
					},
					onTouchMove:function(startTouches, currentTouches){
						if(_this.isSceneLocked()){
							return false;
						}
	
						if(startTouches.length > 0 && currentTouches.length > 0){
							var r = _this.parseTouches(startTouches, currentTouches);
							_this.onTouchMove(r.x, r.y, r.d);
						}
					},
					onTouchEnd:function(startTouches, currentTouches){
						if(_this.isSceneLocked()){
							return false;
						}
						
						if(startTouches.length > 0 && currentTouches.length > 0){
							var r = _this.parseTouches(startTouches, currentTouches);
							_this.onTouchEnd(r.x, r.y, r.d);
						}
					}
				});
			}
			
			if(this.playMusicBtn){
				this.playMusicBtn.bind(touchStart, function(e){
					if($(this).hasClass("playing")){
						$(this).removeClass("playing");
						_this.audio.pause();
						$(this).detach(); //兼容uc无法停止animation
						_this.container.after($(this));
					}
					else{
						$(this).addClass("playing");
						_this.audio.play();
					}
				});
			}
		},
		parseTouches:function(start, current){
			var startTouch =  start[0];
			var currentTouch = current[0];
			var x = currentTouch.pageX - startTouch.pageX;
			var y = currentTouch.pageY - startTouch.pageY;
			var d = currentTouch.timeStamp - startTouch.timeStamp;
			return {
				x:x,
				y:y,
				d:d
			};
		},
		checkThreshold:function(x, y, d){
			var value = this.xType ? x : y;
			if(Math.abs(value) > 100){
				this._touchState = 0;
				return true;
			}
			return false;
		},
		find:function(selector){
			return $(selector, this.container);
		},
		turnNext:function(){
			var newPage = this.getNextPage();
			this.setCurrentPage(newPage);
		},
		turnPrev:function(){
			var newPage = this.getPrevPage();
			this.setCurrentPage(newPage);
		},
		getNextPage:function(){
			var currentIndex = this.getCurrentIndex();
			var index = (currentIndex +1) % this.pages.length;
			return this.pages[index];
		},
		getPrevPage:function(){
			var currentIndex = this.getCurrentIndex();
			var length = this.pages.length;
			var index = (currentIndex - 1 + length) % length;
			return this.pages[index];
		},
		resetPage:function(page, css){
			css = css || {
				"{prefix}transform":"none"
			};
			
			page.addClass("page_transtion");
			page.css(css);
			setTimeout(function(){
				page.removeClass("active_page");
			},500);
		},
		setCurrentPage:function(page){
			var oldPage = this.currentPage;
			this.currentPage = page;
			this.currentPage.show();
			this.currentPage.removeSiblingsClass( "current_page" );
			this.currentPage.addClass("current_page");
			this.resetPage(this.currentPage);
			if(!this.currentPage.isLocked()){
				this.currentPage.onShow();
			}
			var _this = this;
			setTimeout(function(){
				if(oldPage){
					oldPage.onHide();
				}
			},500);
		},
		getActivePage:function(threshold){
			return  threshold * this.dType < 0 ? this.getNextPage() : this.getPrevPage();
		},
		setActivePageClass:function(){
			this.activePage.removeSiblingsClass("active_page");
			this.activePage.addClass("active_page");
		},
		resetActivePage:function(css){
			this.resetPage(this.activePage, css);
		},
		/**
		 * @param x 横轴上滑动距离
		 * @param y 纵轴上滑动距离
		 * @param d (duration) 滑动时间
		 */
		onTouchMove:function(x, y, d){
			throw new Error("Must implement the inherited abstract method onTouchMove()");
		},
		/**
		 * @param x 横轴上滑动距离
		 * @param y 纵轴上滑动距离
		 * @param d (duration) 滑动时间
		 */
		onTouchEnd:function(x, y, d){
			throw new Error("Must implement the inherited abstract method onTouchEnd()");
		},
		getCurrentIndex:function(){
			return this.currentPage.getElement().index();
		},
		refreshPages:function(){
			this.clearAnimateTranstion();
			this.find(".main_page").hide();
			this.find(".current_page, .active_page").show();
		},
		clearAnimateTranstion:function(){
			this.find(".page_transtion").removeClass("page_transtion");	
		},
		isSceneLocked:function(){
			return this.loading || this.currentPage.isLocked();
		}
	};
	SceneBase.extends = function(properties){
		var subClass = function(options){
			this.init(options);
		};
		inherits(subClass, SceneBase, properties);
		return subClass;
	};
	
	/**
	 * 方向向上 
	 */
	SceneBase.TYPE_UP = 0;

	/**
	 * 方向向向下
	 */
	SceneBase.TYPE_DOWN = 1;

	/**
	 * 方向向上 
	 */
	SceneBase.TYPE_LEFT = 2;

	/**
	 * 方向向上 
	 */
	SceneBase.TYPE_RIGHT = 3;
	

	/**
	 * 普通切换方式 
	 */
	SceneBase.STYLE_TRANSLATE = 0;
	
	/**
	 * 覆盖切换方式 
	 */
	SceneBase.STYLE_COVER = 1;
	
	/**
	 * 缩放切换方式 
	 */
	SceneBase.STYLE_SCALE = 2;
	
	/**
	 * 展开切换方式 
	 */
	SceneBase.STYLE_UNFOLD = 3;
	
	/**
	 * 内3D切换方式 
	 */
	SceneBase.STYLE_3D_IN = 4;
	
		/**
	 * 内3D切换方式 
	 */
	SceneBase.STYLE_3D_OUT = 5;
	
	
	/**
	 * 平移效果 
	 */
	var TranslateScene = SceneBase.extends({
		/**
		 * @see(SceneBase.onTouchMove) 
		 */
		onTouchMove:function(x, y, d){
			var data = this.initCoords(x, y);
			var value = data.value;
			var max = data.max;
			var flag = value < 0 ? 1: -1;
			var _value = ( max - Math.abs(value) ) * flag;
			var _max = max * flag;
			var originValue = value > 0 ? "100%": "0%";
			var scale = Math.abs(_value)  / max * 0.9;
			var css = {
				"{prefix}transform":"translate"+data.name+"(" +  _value + "px)"
			};
			var currentCss = {
				"{prefix}transform":"translate"+data.name+"(" + ( _value - _max) + "px)"
			};
	
			this.refreshPages();
			this.activePage = this.getActivePage(value);
			this.setActivePageClass();
			this.activePage.css(css);
			this.currentPage.css(currentCss);
		},
		/**
		 * @see(SceneBase.onTouchEnd) 
		 */
		onTouchEnd:function(x, y, d){
			var data = this.initCoords(x, y);
			var value = data.value;
			var speed = Math.abs(value / d);
			var max = data.max;
			var tValue = value > 0 ? max : -max;
			
			if(speed > this.threshold || this.checkThreshold(x, y, d)){
				var css = {
					"{prefix}transform":"translate"+data.name+"(" +  tValue  + "px)"
				};
				this.currentPage.addClass("page_transtion");
				this.currentPage.css(css);
				if(value * this.dType > 0){
					this.turnPrev();
				}
				else{
					this.turnNext();
				}
				
			}
			else{
				var currentCss = {
					"{prefix}transform":"translate"+data.name+"(0px)"
				};
				var activeCss = {
					"{prefix}transform":"translate"+data.name+"(" +  -tValue + "px)"
				};
				this.currentPage.addClass("page_transtion");
				this.currentPage.css(currentCss);
				this.resetActivePage(activeCss);
			}
		}
	});
	
	
	/**
	 * 普通平面效果 
	 */
	var CoverScene = SceneBase.extends({
		/**
		 * @see(SceneBase.onTouchMove) 
		 */
		onTouchMove:function(x, y, d){
			var data = this.initCoords(x, y);
			var max = data.max;
			var value = data.value;
			var _value = ( max - Math.abs(value) ) * (value < 0 ? 1: -1);
			var	css = {
				"{prefix}transform":"translate"+data.name+"(" +  _value  + "px)"
			};
			this.refreshPages();
			this.activePage = this.getActivePage(value);
			this.setActivePageClass();
			this.activePage.css(css);
		},
		/**
		 * @see(SceneBase.onTouchEnd) 
		 */
		onTouchEnd:function(x, y, d){
			var data = this.initCoords(x, y);
			var max = data.max;
			var value = data.value;
			var speed = Math.abs(value / d);
			
			if(speed > this.threshold || this.checkThreshold(x, y, d)){
				if(value * this.dType > 0){
					this.turnPrev();
				}
				else{
					this.turnNext();
				}
			}
			else{
				var _value = value < 0 ?  max : -max;
				var	css = {
					"{prefix}transform":"translate"+data.name+"(" +  _value  + "px)"
				};
				this.resetActivePage(css);
			}
		}
	});
	
	/**
	 * 缩放平面效果 
	 */
	var ScaleScene = SceneBase.extends({
		/**
		 * @see(SceneBase.onTouchMove) 
		 */
		onTouchMove:function(x, y, d){
			var data = this.initCoords(x, y);
			var value = data.value;
			var max = data.max;
			var _value = ( max - Math.abs(value) ) * (value < 0 ? 1: -1);
			var originValue = value > 0 ? "100%": "0%";
			var scale = Math.abs(_value)  / max * 0.9;
			var css = {
				"{prefix}transform":"translate"+data.name+"(" +  _value  + "px)"
			};
			var currentCss = {
				"{prefix}transform-origin": (this.xType == 0 ? ("50% "+originValue) : (originValue +" 50%")),
				"{prefix}transform":"scale("+scale+", "+scale+")"
			};
	
			this.refreshPages();
			this.activePage = this.getActivePage(value);
			this.setActivePageClass();
			this.activePage.css(css);
			this.currentPage.css(currentCss);
			
		},
		/**
		 * @see(SceneBase.onTouchEnd) 
		 */
		onTouchEnd:function(x, y, d){
			var data = this.initCoords(x, y);
			var value = data.value;
			var speed = Math.abs(value / d);
			var max = data.max;
			var tValue = value < 0 ? max : -max;
			var activeCss = {
				"{prefix}transform":"translate"+data.name+"(" +  tValue  + "px)"
			};
			
			if(speed > this.threshold || this.checkThreshold(x, y, d)){
				var css = {"{prefix}transform":"scale(0, 0)"};
				this.currentPage.addClass("page_transtion");
				this.currentPage.css(css);
				if(value * this.dType > 0){
					this.turnPrev();
				}
				else{
					this.turnNext();
				}
				
			}
			else{
				var currentCss = {"{prefix}transform":"scale(1, 1)"};
				this.currentPage.addClass("page_transtion");
				this.currentPage.css(currentCss);
				this.resetActivePage(activeCss);
			}
		}
	});
	
	var UnfoldScene = SceneBase.extends({
		/**
		 * @see(SceneBase.onTouchMove) 
		 */
		onTouchMove:function(x, y, d){
			var data = this.initCoords(x, y);
			var max = data.max;
			var value = data.value;
			var tValue = value > 0 ? max : -max; 
			var deg = Math.acos((max - Math.abs(value)) / max) * 180 / Math.PI;
			if(deg > 90){
				deg = 90;
			}
			var styleName = this.xType ? "width" : "height";
			var activeCss = {
				"{prefix}transform": "rotate"+data.other+"(" +  (90 - deg)  + "deg)"
			};
			this.refreshPages();
			this.activePage = this.getActivePage(value);
			this.setActivePageClass();
			this.activePage.css(activeCss);
		},
		/**
		 * @see(SceneBase.onTouchEnd) 
		 */
		onTouchEnd:function(x, y, d){
			var data = this.initCoords(x, y);
			var max = data.max;
			var value = data.value;
			var speed = Math.abs(value / d);
			var deg = Math.acos((max - Math.abs(value)) / max) * 180 / Math.PI;
			if(deg > 90){
				deg = 90;
			}
			
			var recoverActiveCss = {
				"{prefix}transform": "rotate"+data.other+"(" +  90  + "deg)"
			};
			
			if(speed > this.threshold || this.checkThreshold(x, y, d)){
				if(value *  this.dType > 0){
					this.turnPrev();
				}
				else{
					this.turnNext();
				}
			}
			else{
				this.resetActivePage(recoverActiveCss);
			}
		}
	});
	
	/**
	 * 内3D效果 
	 */
	var Scene3DIn = SceneBase.extends({
		/**
		 * @see(SceneBase.onTouchMove) 
		 */
		onTouchMove:function(x, y, d){
			var data = this.initCoords(x, y);
			var name = data.name;
			var other = data.other;
			var value = data.value;
			var speed =  Math.abs(value / d);
			var max = data.max;
			var tValue = value > 0 ? max : -max; 
			var deg = Math.acos((max - Math.abs(value)) / max) * 180 / Math.PI;
			if(deg > 90){
				deg = 90;
			}
			var originValue = value > 0 ? "100%": "0%";
			var flag = value < 0 ? 1 : -1;
			var _value = ( max - Math.abs(value) ) * flag;
			var opacity = 1 - deg /60 ;
			if(opacity<0){
				opacity=0;
			}
			
			deg = this.xType ? deg * flag : -deg * flag; 

			var css = {
				"opacity":1,
				"{prefix}transform":"translate"+name+"(" + _value  + "px)"
			};
			
			var currentCss = {
				"{prefix}transform-origin": (this.xType == 0 ? ("50% "+originValue) : (-originValue +" 50%")),
				"opacity": opacity,
				"{prefix}transform":"perspective(200px) rotate"+other+"("+ ( deg )+"deg) translate"+name+"("+value+"px)"
			};
			
			this.refreshPages();
			this.activePage = this.getActivePage(value);
			this.setActivePageClass();
			this.activePage.css(css);
			this.currentPage.css(currentCss);
			
		},
		/**
		 * @see(SceneBase.onTouchEnd) 
		 */
		onTouchEnd:function(x, y, d){
			var data = this.initCoords(x, y);
			var name = data.name;
			var other = data.other;
			var value = data.value;
			var speed =  Math.abs(value / d);
			var max = data.max;
			var tValue = value < 0 ? max : -max; 
			var deg = Math.acos((max - Math.abs(value)) / max) * 180 / Math.PI;
			var flag = value > 0 ? 1:-1;
			if(this.xType){
				flag *=-1;
			}
			var recoverCss = {
				"opacity": 1,
				"{prefix}transform":"perspective(200px) rotate"+other+"(0deg) translate"+name+"(0px)"
			};
			var recoverActiveCss = {
				"{prefix}transform":"translate"+name+"(" + ( tValue ) + "px)"
			};
			var currentCss = {
				"opacity": 0.2,
				"{prefix}transform":"perspective(200px) rotate"+other+"("+ (90 * flag)  +"deg) translate"+name+"("+ -tValue +"px)"
			};
			
			
			if(speed > this.threshold || this.checkThreshold(x, y, d)){
				this.currentPage.addClass("page_transtion");
				this.currentPage.css(currentCss);
				if(value *  this.dType > 0){
					this.turnPrev();
				}
				else{
					this.turnNext();
				}
			}
			else{
				this.currentPage.addClass("page_transtion");
				this.currentPage.css(recoverCss);
				this.resetActivePage(recoverActiveCss);
			}
		}
	});
	
	/**
	 * 内3D效果 
	 */
	var Scene3DOut = SceneBase.extends({
		/**
		 * @see(SceneBase.onTouchMove) 
		 */
		onTouchMove:function(x, y, d){
			var data = this.initCoords(x, y);
			var name = data.name;
			var other = data.other;
			var value = data.value;
			var speed =  Math.abs(value / d);
			var max = data.max;
			var tValue = value > 0 ? max : -max; 
			var deg = Math.acos((max - Math.abs(value)) / max) * 180 / Math.PI;
			if(deg > 90){
				deg = 90;
			}
			var originValue = "0%";
			var originValue2 = "100%";
			if(value < 0){
				originValue = "100%";
				originValue2 = "0%";
			}
			var flag = value < 0 ? 1 : -1;
			var _value = ( max - Math.abs(value) ) * flag;
			var opacity = 1 - deg /60 ;
			if(opacity<0){
				opacity=0;
			}
			
			deg = this.xType ? -deg * flag : deg * flag;
			var activeDeg = flag * (Math.abs(deg) - 90);
			var activeCss = {
				"opacity":1,
				"{prefix}transform":"translate"+name+"(" + _value  + "px)"
			};
			
			var currentCss = {
				"opacity": 1,
				"{prefix}transform":"translate"+name+"("+ value +"px)"
			};
			
			var currentContainerCss = {
				"{prefix}transform-origin": (this.xType == 0 ? ("50% "+originValue) : (-originValue +" 50%")),
				"{prefix}transform":"perspective(800px) rotate"+other+"("+ deg +"deg)"
			};
			
			var activeContainerCss = {
				"{prefix}transform-origin": (this.xType == 0 ? ("50% "+originValue2) : (-originValue2 +" 50%")),
				"{prefix}transform":"perspective(800px) rotate"+other+"("+ activeDeg +"deg)"
			};
			
			this.refreshPages();
			this.activePage = this.getActivePage(value);
			this.setActivePageClass();
			this.activePage.css(activeCss);
			this.currentPage.css(currentCss);
			this.activePage.setContainerStyle(activeContainerCss);
			this.currentPage.setContainerStyle(currentContainerCss);
			
			
		},
		/**
		 * @see(SceneBase.onTouchEnd) 
		 */
		onTouchEnd:function(x, y, d){
			var data = this.initCoords(x, y);
			var name = data.name;
			var other = data.other;
			var value = data.value;
			var speed =  Math.abs(value / d);
			var max = data.max;
			var tValue = value < 0 ? max : -max; 
			var deg = Math.acos((max - Math.abs(value)) / max) * 180 / Math.PI;
			var flag = value > 0 ? 1:-1;
			if(this.xType){
				flag *=-1;
			}
			var recoverCss = {
				"opacity": 1,
				"{prefix}transform":"perspective(800px) rotate"+other+"(0deg) translate"+name+"(0px)"
			};
			var recoverActiveCss = {
				"{prefix}transform":"translate"+name+"(" + ( tValue ) + "px)"
			};
			var currentCss = {
				"opacity": 1,
				"{prefix}transform":"translate"+name+"("+ (-tValue) +"px)"
			};
			
			var currentContainerCss = {
				"{prefix}transform":"perspective(800px) rotate"+other+"("+ (-90 * flag)  +"deg)"
			};
		
			if(speed > this.threshold || this.checkThreshold(x, y, d)){
				this.currentPage.addClass("page_transtion");
				this.currentPage.css(currentCss);
				this.currentPage.addContainerClass("page_transtion");
				this.currentPage.setContainerStyle(currentContainerCss);
				if(value *  this.dType > 0){
					this.turnPrev();
				}
				else{
					this.turnNext();
				}
			}
			else{
				this.currentPage.addClass("page_transtion");
				this.currentPage.css(recoverCss);
				this.currentPage.addContainerClass("page_transtion");
				this.currentPage.setContainerStyle({
					"{prefix}transform":"perspective(800px) rotate"+other+"(0deg)"
				});
				this.resetActivePage(recoverActiveCss);
				this.activePage.setContainerStyle({
					"{prefix}transform":"perspective(800px) rotate"+other+"("+(flag*90)+"deg)"
				});
				
			}
		},
		resetPage:function(page, css){
			css = css || {
				"{prefix}transform":"none"
			};
			page.removeClass("active_page")
			page.addClass("page_transtion");
			page.css(css);
			page.addContainerClass("page_transtion");
			page.setContainerStyle(css);
		}
	});

	
	window.SceneManager = SceneManager;
	
	
})();

